package com.qingmu.club.minaapi.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class HttpUtils {

    private static HttpUtils httpUtils;
    private OkHttpClient okHttpClient;

    @Value("${web.imageService}")
    private static String wanPath;

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private HttpUtils() {
        okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder().
                connectTimeout(10, TimeUnit.SECONDS).
                readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS);

    }

    //创建 单例模式（OkHttp官方建议如此操作）
    public static HttpUtils getInstance() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    static private Request.Builder getGetBuilder(String url, Map<String, String> params, Map<String, String> heads) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        if (params != null) {
            for (String key : params.keySet()) {
                urlBuilder.addQueryParameter(key, params.get(key));
            }
        }


        reqBuild.url(urlBuilder.build());
        if (heads != null) {
            for (String key : heads.keySet()) {
                reqBuild.addHeader(key, heads.get(key));
            }
        }

        return reqBuild;
    }






    static public String requestGet(String url, Map<String, String> params, Map<String, String> heads) throws CommonException {
        Request.Builder reqBuild = getGetBuilder(url, params, heads);
        Request req = reqBuild.build();

        try {
            Response response = OkHttpUtil.execute(req);
            //判断请求是否成功
            if (response.isSuccessful()) {
                String content = response.body().string();
                logger.info("GET Response" + content);
                return content;
                //打印服务端返回结果
            } else {
                String content = response.body().string();
                logger.info("ERROR Response" + content);
                throw new CommonException(response.code(), response.message());
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
            throw new CommonException(505, e.getMessage());
        }
    }

    static public String requestGetYB(String url, Map<String, String> params, Map<String, String> heads, Callback callback) {
        Request.Builder reqBuild = getGetBuilder(url, params, heads);
        Request req = reqBuild.build();

        try {
            OkHttpUtil.enqueue(req, callback);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
        }
        return "ok";
    }


    static private Request.Builder getBodyBuilder(String url, String json, Map<String, String> heads) {
        logger.info("requestPostBody url:" + url);
        logger.info("body:" + json);
        MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSONType, json);
        Request.Builder builder = new Request.Builder();

        builder.url(url);

        if (heads != null) {
            for (String key : heads.keySet()) {

                builder.addHeader(key, heads.get(key));
            }
        }
        builder.post(body);
        return builder;
    }

    static private Request.Builder getFormBuilder(String url, Map<String, String> params, Map<String, String> heads) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();

        logger.info("form url:" + url);
        logger.info("params:" + params.toString());

        try {
            if (params != null) {
                for (String key : params.keySet()) {
                    if (StringUtils.isNotEmpty(params.get(key))) {
                        bodyBuilder.add(key, params.get(key));
                    } else {
                        bodyBuilder.add(key, "");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

        RequestBody body = bodyBuilder.build();
        Request.Builder builder = new Request.Builder();

        if (heads != null) {
            for (String key : heads.keySet()) {

                builder.addHeader(key, heads.get(key));
            }
        }
        builder.url(url);
        builder.post(body);

        return builder;

    }


    static public String requestPostBody(String url, String json, Map<String, String> heads) throws CommonException {


        Request.Builder builder = getBodyBuilder(url,json,heads);
        Request req = builder.build();

        try {
            Response response = OkHttpUtil.execute(req);
            logger.error(response.toString());
            if (response.isSuccessful()) {


                String returnString = response.body().string();

                logger.info("success " + returnString);

                return returnString;
                //打印服务端返回结果

            } else {

                logger.error("failure: " + response.body().string());

                throw new CommonException(response.code(), response.message());
            }
            //throw   new ApiException(response.code(),response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
            throw new CommonException(505, e.getMessage());


        }


    }

    static public String requestPostBodyYB(String url, String json, Map<String, String> heads, Callback cb) {
        Request.Builder builder = getBodyBuilder(url,json,heads);
        Request req = builder.build();
        try {
            OkHttpUtil.enqueue(req, cb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    static public String requestPostForm(String url, Map<String, String> params, Map<String, String> heads) throws CommonException {



        Request.Builder builder = getFormBuilder(url,params,heads);
        Request req = builder.build();

        try {
            Response response = OkHttpUtil.execute(req);
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new CommonException(response.code(), response.message());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(505, e.getMessage());
        }
    }

    static public String requestPostFormYB(String url, Map<String, String> params, Map<String, String> heads, Callback cb) {

        Request.Builder builder = getFormBuilder(url,params,heads);
        Request req = builder.build();
        try {
            OkHttpUtil.enqueue(req, cb);
            //打印服务端返回结果
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }

    public String downloadFile(String path, String url, String json, Map<String, String> heads){

        MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSONType, json);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (heads != null) {
            for (String key : heads.keySet()) {
                builder.addHeader(key, heads.get(key));
            }
        }

        builder.post(body);
        Request req = builder.build();


        InputStream is = null;
        FileOutputStream fos = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dateString = df.format(new Date());
        String newFilePath = path + "/upload/miniqrcode/" + dateString + "/";
        String newFileName = new Date().getTime() + ".png";
        File checkFile = new File(newFilePath);
        if (!checkFile.exists() && !checkFile.isDirectory()) {
            checkFile.mkdirs();
        }

        try {
            Response response = okHttpClient.newCall(req).execute();
            if (response.isSuccessful()) {
                byte[] buf = new byte[1024];
                int len = 0;
                is = response.body().byteStream();
                File file = new File(newFilePath, newFileName);

                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                //如果下载文件成功，第一个参数为文件的绝对路径
            } else {
                return null;
            }
        } catch (IOException e) {
            System.out.println("数据获取失败");
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }

        return "/miniqrcode/" + dateString + "/" + newFileName;

    }

//    新创建积分商品二维码路径


}
